package com.hang.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hang.entity.Dict;
import com.hang.exception.MyException;
import com.hang.exception.MyExceptionEnum;
import com.hang.mapper.DictMapper;
import com.hang.model.dto.response.DictDTO;
import com.hang.service.IDictService;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

/**
 *
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict>
    implements IDictService {

    /**
     * 获取所有的字典集合
     * @return
     */
    @Override
    public List<DictDTO> getAllDict() {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.lambda().eq(Dict::getParentId,1L);

        //获取所有根节点的分类
        List<Dict> dictList = this.baseMapper.selectList(dictQueryWrapper);
        return packageDictDTO(dictList);
    }

    /**
     * 获取指定字典的下拉选择
     * @param value
     * @return
     */
    @Override
    public List<DictDTO> getDictByValue(String value) {
        if(StrUtil.isBlank(value)){
            throw new MyException(MyExceptionEnum.ID_IS_NULL);
        }

        Long parentId = Long.valueOf(value);

        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper
                .lambda()
                .eq(Dict::getParentId,parentId);


        List<Dict> dictList = this.baseMapper.selectList(dictQueryWrapper);
        return packageSelectDictDTO(dictList);
    }

    private List<DictDTO> packageDictDTO(List<Dict> dictList){
        List<DictDTO> dictDTOList = new LinkedList<>();
        dictList.forEach(
                dict -> {
                    DictDTO dictDTO = new DictDTO();
                    dictDTO.setValue(String.valueOf(dict.getDictId()));
                    dictDTO.setLabel(dict.getName());
                    dictDTOList.add(dictDTO);
                }
        );

        return dictDTOList;
    }

    private List<DictDTO> packageSelectDictDTO(List<Dict> dictList){
        List<DictDTO> dictDTOList = new LinkedList<>();
        dictList.forEach(
                dict -> {
                    DictDTO dictDTO = new DictDTO();
                    dictDTO.setValue(String.valueOf(dict.getValue()));
                    dictDTO.setLabel(dict.getName());
                    dictDTOList.add(dictDTO);
                }
        );

        return dictDTOList;
    }
}




